/**
 * 
 */
package org.picWeb.util.preferences;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zjm
 * @version 1.0 org.picWeb.util.preferences/Variable.java 2011-7-19
 */
public class Variable {

	private String pre;
	private String post;

	private VariableStore variables;

	private Map<String, String> cache;

	public Variable(VariableStore store, String pre, String post) {
		this.pre = pre;
		this.post = post;
		this.variables = store;
		cache = new HashMap<String, String>();
	}

	public void clearCache() {
		cache.clear();
	}

	public String expandVariables(String source) {
		if (null == source) {
			return source;
		}
		
		String result = (String) this.cache.get(source);
		if (null != result) {
			return result;
		}

		int fIndex = source.indexOf(this.pre);

		if (fIndex == -1) {
			return source;
		}

		StringBuffer sb = new StringBuffer(source);

		while (fIndex > -1) {
			int lIndex = sb.indexOf(post);
			int start = fIndex + pre.length();

			if (lIndex < start) {
				lIndex = sb.indexOf(post, lIndex + 1);
			}

			String valName = sb.substring(start, lIndex);
			sb.replace(fIndex, lIndex + 1, variables.getVariableValue(valName));

			fIndex = sb.indexOf(pre);
		}

		result = sb.toString();

		cache.put(source, result);

		return result;
	}
}
